import { defineStore } from "pinia";
import common_util from "../util/common_util";
import router from "@/router";
import { ElMessage ,ElMessageBox} from "element-plus";
import { toRaw } from "vue";
import _common_util from "@/util/common_util.js";

export const useUserStore = defineStore("user", {
  state: () => ({
    // role: "INSTRUCTOR", // 这里存储用户的角色信息
    // user: {
    //   id: 10,
    //   name: "XU55",
    //   roleId: 2,
    //   stage: "intern",
    //   isDeleted: 0,
    //   createdAt: "",
    //   updatedAt: "",
    // },
    role: null,
    user: { id: 13 },
    menus: [], // 用于存储菜单数据
    token: null, // 存储用户的 token
    myClass: [],
    myExam: [],
    myNotes: [], // 存储用户的笔记

    /*
     * 教师创建：考试、课程
     * */
    teacher_myCourse: [],
    teacher_myExam: [],
    createdExam: {
      examSectionName: "",
      courseName: "",
      title: "",
      description: "",
      startTime: "",
      endTime: "",
      creatorId: 0,
    },
    createdCourse: {
      title: "测试标题",
      categoryName: "基础护理",
      difficulty: 0,
      lastingTime: 0,
      description: "测试描述",
      //courseCover: null,
      createdBy: 0,
      //status: 0,
    },
    editedCourse: {
      course: {
        id: 0,
        title: "",
        description: "",
        status: 0,
        lastingTime: 0,
        difficulty: 0,
        categoryName: "",
        coverUrl: "",
        version: 0,
        createdBy: 0,
        createdAt: "",
      },
    },
    courseNow: {
      id: 0,
      title: "",
      description: "",
      status: 0,
      lastingTime: 0,
      difficulty: 0,
      categoryName: "",
      coverUrl: "",
      version: 0,
      createdBy: 0,
      createdAt: "",
    },
  }),
  getters: {
    getCreatedById: (state) => state.createdCourse.createdBy === state.user.id,
    isStudent: (state) => state.role === "student",
    isTeacher: (state) => state.role === "teacher",
    isAdmin: (state) => state.role === "admin",
  },
  actions: {
    cleanCourse() {
      this.createdCourse = {
        title: "",
        categoryName: "",
        difficulty: 0,
        lastingTime: 0,
        description: "",
        courseCover: null,
        createdBy: this.user.id,
        status: 0,
      };
    },
    setRole(role) {
      this.role = role;
    },
    // 登录
    login(username, password, onSuccess, onFailure) {
      // 调用您封装的 post 方法
      common_util.post(
        "/api/user/login",
        {
          username,
          password,
        },
        {}, // params, 这里为空
        (data) => {
          // --- 成功回调，在这里处理所有业务逻辑 ---
          ElMessage.success("登录成功！");

          // 1. 存储核心数据到 Pinia state
          this.user = data.user;
          this.token = data.token;
          // this.menus = data.menus; // 如果有菜单数据也一并存储
          common_util.storeAccessToken(data.token);
          // 2. 根据 roleId 设置角色
          switch (data.user.roleId.toString()) {
            case "1":
              this.setRole("admin");
              break;
            case "2":
              this.setRole("teacher");
              break;
            case "3":
              this.setRole("student");
              break;
            default:
              console.warn("未知角色ID:", data.user.roleId);
              this.setRole("student"); // 设置一个默认角色
              break;
          }
          common_util.storeAccessToken(data.token);
          // 3. 执行路由跳转
          router.push("/" + this.role + "/" + this.role + "-dashboard");

          // 4. 如果组件传入了成功回调，则执行
          if (onSuccess) onSuccess(data);
        },
        (message) => {
          // --- 失败回调 ---
          const errorMsg = message || "用户名或密码错误，请重试";
          // 2. 在提示框中使用这个保证有值的 errorMsg
          ElMessage.error(`登录失败: ${errorMsg}`);
          if (onFailure) onFailure(errorMsg);
        },
      );
    },
    logout() {
      // 重置 state 到初始状态
      this.$reset();
      common_util.deleteAccessToken();
      // a-plugin-persistedstate 会自动清除 storage 中的数据

      // 跳转到登录页
      router.push("/login");
      //ElMessage.success("您已成功退出登录！");
    },
    /**
 * @description 修改当前用户密码
 * @param {string} oldPassword - 旧密码
 * @param {string} newPassword - 新密码
 * @param {function} [onSuccess] - 成功回调
 * @param {function} [onFailure] - 失败回调
 */
    changePassword(oldPassword, newPassword, onSuccess, onFailure) {
      common_util.post(
        "/api/user/change-password",
        { oldPassword, newPassword },
        {}, // params
        (data) => {
          ElMessage.success("密码修改成功！");
          if (onSuccess) onSuccess(data);
        },
        (message) => {
          ElMessage.error(`密码修改失败: ${message}`);
          if (onFailure) onFailure(message);
        }
      );
    },

    /**
     * @description 更新当前用户的基本信息
     * @param {object} basicInfo - 包含 name, age, email, phone 的对象
     * @param {function} [onSuccess] - 成功回调
     * @param {function} [onFailure] - 失败回调
     */
    modifyBasicInfo(basicInfo, onSuccess, onFailure) {
      common_util.put(
        "/api/user/basic-info",
        basicInfo,
        {}, // params
        (data) => {
          // 更新成功后，用返回的最新数据更新 Pinia state
          this.user = data.user;
          ElMessage.success("基本信息更新成功！");
          if (onSuccess) onSuccess(data);
        },
        (message) => {
          ElMessage.error(`信息更新失败: ${message}`);
          if (onFailure) onFailure(message);
        }
      );
    },

    /**
     * @description 注销当前用户的账户
     * @param {function} [onSuccess] - 成功回调
     * @param {function} [onFailure] - 失败回调
     */
    cancelAccount(onSuccess, onFailure) {
      ElMessageBox.confirm(
        '您确定要注销您的账户吗？此操作不可撤销。',
        '警告',
        {
          confirmButtonText: '确定注销',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        // common_util.delete(
        //   "/api/user/account",
        //   {}, // params
        //   (data) => {
        //     ElMessage.success("账户已成功注销！");
        //     // 注销成功后，执行退出登录的逻辑
        //     this.logout();
        //     if (onSuccess) onSuccess(data);
        //   },
        //   (message) => {
        //     ElMessage.error(`账户注销失败: ${message}`);
        //     if (onFailure) onFailure(message);
        //   }
        // );
        router.push("/login");
        ElMessage.success("账户已成功注销！");
      }).catch(() => {
        ElMessage.info('已取消注销操作');
      });
    },

    /**
     * @description (管理员) 获取所有用户列表
     * @param {function} [onSuccess] - 成功回调
     * @param {function} [onFailure] - 失败回调
     */
    fetchAllUsers(onSuccess, onFailure) {
      common_util.get(
        "/api/user/list",
        {}, // params
        (data) => {
          // 这个方法通常由管理员页面调用，数据不直接存入 Pinia state，
          // 而是通过回调函数传递给调用方。
          if (onSuccess) onSuccess(data);
        },
        (message) => {
          ElMessage.error(`获取用户列表失败: ${message}`);
          if (onFailure) onFailure(message);
        }
      );
    },
    async register(registrationData, onRegisterSuccess, onRegisterFailure) {
      // 使用您项目中的通用 callback 风格
      common_util.post(
        "/api/user/register",
        registrationData,
        {},
        (data) => {
          ElMessage.success("操作成功！"); // 提示语改为更通用的"操作成功"

          // 关键修改：判断当前登录用户的角色
          if (this.user && this.user.roleId === 1) {
            // 如果是管理员操作，则刷新用户列表以实现数据同步
            this.fetchAllUsers();
          } else {
            // 如果是普通用户注册，则跳转到登录页
            router.push('/login');
          }

          if (onRegisterSuccess) {
            onRegisterSuccess(data);
          }
        },
        (message) => {
          // 失败回调
          ElMessage.error(`注册失败: ${message}`);

          // 如果组件传了 onFailure 回调，就执行它
          if (onRegisterFailure) onRegisterFailure(message);
        },
      );
    },

    /*学生*/
    /*
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     获取信息
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   */
    async getMyCourse() {
      await common_util.get(
        '/api/study/selections',
        {},
        (data) => {
          this.myClass = data;
          console.log(data);
        },
      );
      // common_util.get(
      //   `/api/study/selections/${this.user.id}`,
      //   {},
      //   (data) => { },
      // );
    },
    getMyExam() {
      common_util.get(`/api/exam/${this.user.id}`, {}, (data) => { });
    },
    getMyNote(courseId) {
      common_util.get(
        `/api/study/notes`,
        {
          userId: this.user.id,
          courseId: courseId,
        },
        (data) => { 
          this.myNotes = data || [];
        },
      );
    },
    getProgress() { },
    getAnswers() { },
    getAsks() { },
    /*
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    上传信息
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    */
    postNote(courseId, content) {
      return new Promise((resolve, reject) => {
        common_util.post("/api/study/note", {
          userId: this.user.id,
          courseId: courseId,
          content: content,
        }, {}, (data) => {
          ElMessage.success("笔记保存成功");
          resolve(data);
        }, (error) => {
          reject(error);
        });
      });
    },
    selectCourse(courseId) {
      return new Promise((resolve, reject) => {
        common_util.post(
          "/api/study/select",
          {
            courseId,
            userId: this.user.id,
          },
          {},
          (data) => {
            // 根据后端返回的消息判断是否成功
            if (data && (data.includes("选课成功") || data.includes("您已选过该课程"))) {
              ElMessage.success(data);
              resolve(data);
            } else {
              reject(new Error(data || "选课失败"));
            }
          },
          (message) => {
            reject(new Error(message));
          }
        );
      });
    },
    postAsk() { },
    postAnswer() { },

    /*
     * 教师
     */
    /*创建*/
    selectTeacherCourse(teacherId) {
      console.log("查找课程" + teacherId);
      this.teacher_myCourse = [];
      common_util.get(
        "/api/courses/by-teacher",
        { teacherId: teacherId },
        (data) => {
          console.log("common_util.get 返回的 data: ", data);
          this.teacher_myCourse = Array.isArray(data) ? data : [];
        },
      );
    },
    changeEditedCourse(courseId) {
      console.log(this.teacher_myCourse);

      this.editedCourse = Array.isArray(this.teacher_myCourse)
        ? this.teacher_myCourse.filter((item) => item.course.id === courseId)[0]
        : [];
      console.log("???");
      console.log(this.editedCourse);
    },
    // changeEditedCourse(courseObject) {
    //   // 这个方法现在直接接收完整的课程对象
    //   // 不再需要从自己的列表中查找
    //   this.editedCourse = courseObject;
    // },
    selectTeacherExam(teacherName) {
      const nameToSearch = teacherName || this.user.name;
      this.teacher_myExam = [];
      console.log("查找考试" + nameToSearch);
      common_util.get("/api/exams", { creatorName: nameToSearch }, (data) => {
        this.teacher_myExam = data;
      });
    },
    async addCourse() {
      console.log("添加课程");
      this.createdCourse.createdBy = this.user.id;
      common_util
        .post("/api/courses/upload", toRaw(this.createdCourse), {}, (data) => {
          ElMessage.success("课程创建成功");
          this.cleanCourse();
          this.teacher_myCourse = [
            {
              course: {
                id: 0,
                title: "",
                description: "",
                status: 0,
                lastingTime: 0,
                difficulty: 0,
                categoryName: "",
                coverUrl: "",
                version: 0,
                createdBy: 0,
                createdAt: "",
                star: 0,
              },
              selectNumber: 0,
              teacher: {
                id: 0,
                name: "",
                roleId: 0,
                stage: "",
                isDeleted: 0,
                createdAt: "",
                updatedAt: "",
              },
            },
          ];
        })
        .then(() => {
          this.selectTeacherCourse(this.user.id);
        });
    },

    deleteCourse(courseId) {
      common_util.delete(`/api/courses/${courseId}`, {}, (data) => {
        console.log("delete" + courseId);

        this.teacher_myCourse = [
          {
            course: {
              id: 0,
              title: "",
              description: "",
              status: 0,
              lastingTime: 0,
              difficulty: 0,
              categoryName: "",
              coverUrl: "",
              version: 0,
              createdBy: 0,
              createdAt: "",
              star: 0,
            },
            selectNumber: 0,
            teacher: {
              id: 0,
              name: "",
              roleId: 0,
              stage: "",
              isDeleted: 0,
              createdAt: "",
              updatedAt: "",
            },
          },
        ];
        if (this.isTeacher) {
          this.selectTeacherCourse(this.user.id);
          return;
        }
        if (this.isAdmin) {
          console.log("isAdmin");
          this.getCourses();
        }
      });
    },
    createExam() {
      this.createdExam.creatorId = this.user.id;
      common_util.post("/api/exams", toRaw(this.createdExam), {}, (data) => {
        this.teacher_myExam = [
          {
            exam: {
              id: 0,
              sectionId: 0,
              courseId: 0,
              creatorId: 0,
              title: "",
              description: "",
              startTime: "",
              endTime: "",
              examType: {},
              status: "",
              createTime: "",
              isDelete: 0,
            },
            examSection: {
              id: 0,
              name: "",
              description: "",
              createTime: "",
            },
          },
        ];
        this.selectTeacherExam("李老师");
        ElMessage.success("考核已创建并发布！");
      });
    },
    updateExam(exam) {
      console.log(exam);
    },
    async getCourses() {
      _common_util.get("/api/courses", {}, (data) => {
        this.teacher_myCourse = data;
      });
    },
    deleteExam(examId) {
      common_util.delete(`/api/exams/${examId}`, {}, (data) => { });
      this.teacher_myExam = [
        {
          exam: {
            id: 0,
            sectionId: 0,
            courseId: 0,
            creatorId: 0,
            title: "",
            description: "",
            startTime: "",
            endTime: "",
            examType: {},
            status: "",
            createTime: "",
            isDelete: 0,
          },
          examSection: {
            id: 0,
            name: "",
            description: "",
            createTime: "",
          },
        },
      ];
    },
    updatePic() { },
    updateExamSection() { },
    updateCoursePart() {
      common_util.patch(
        `/api/courses/${this.editedCourse.course.id}`,
        {
          id: this.editedCourse.course.id,
          title: this.editedCourse.course.title,
          description: this.editedCourse.course.description,
          status: 0,
          lastingTime: this.editedCourse.course.lastingTime,
          difficulty: this.editedCourse.course.difficulty,
          categoryName: this.editedCourse.course.categoryName,
          coverUrl: this.editedCourse.course.coverUrl,
          star: this.editedCourse.course.star,
        },
        {},
        (data) => {
          this.teacher_myCourse = [
            {
              course: {
                id: 0,
                title: "",
                description: "",
                status: 0,
                lastingTime: 0,
                difficulty: 0,
                categoryName: "",
                coverUrl: "",
                version: 0,
                createdBy: 0,
                createdAt: "",
                star: 0,
              },
              selectNumber: 0,
              teacher: {
                id: 0,
                name: "",
                roleId: 0,
                stage: "",
                isDeleted: 0,
                createdAt: "",
                updatedAt: "",
              },
            },
          ];
          this.selectTeacherCourse(this.user.id);
        },
      );
    },
    /*
     * 管理员
     */
  },
  persist: {
    storage: sessionStorage,
  },
});
